package com.choosefine.springboot.devops.system.controller;


import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.result.ReturnMSG;
import com.choosefine.springboot.devops.system.dto.InsertSystemDTO;
import com.choosefine.springboot.devops.system.dto.LoginDTO;
import com.choosefine.springboot.devops.system.dto.UpdateSystemDTO;
import com.choosefine.springboot.devops.system.model.System;
import com.choosefine.springboot.devops.system.service.SystemService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/system")
public class SystemController {
	@Autowired
	private SystemService systemService;
	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping("/{id}")
	public String selectById(@PathVariable("id") Integer id) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		return objectMapper.writeValueAsString(returnMSG.success(systemService.selectById(id)));
	}

	@PostMapping()
	public String insert(@Valid InsertSystemDTO insertSystem, BindingResult result) throws JsonProcessingException {
 		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			System param=new System();
			BeanUtils.copyProperties(insertSystem,param);
			systemService.save(System.class, MapUtil.transBean2Map(param));
			return objectMapper.writeValueAsString(returnMSG.success());
		}
	}

	@PostMapping("/login")
	public String login(@Valid LoginDTO loginDTO, BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.error());
		}else{
			return objectMapper.writeValueAsString(systemService.login(loginDTO));
		}
	}

	@PutMapping()
	public String upate(@Valid UpdateSystemDTO updateSystemDTO,BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.error());
		}else{
			return objectMapper.writeValueAsString(systemService.update(System.class,MapUtil.transBean2Map(updateSystemDTO)));
		}
	}

}
